package ch.ffhs.ks.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;

public class Folder implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Account account;
	private String name;
	private boolean isImapFolder;
	private ArrayList<Mail> mails = new ArrayList<Mail>();

	private ArrayList<Folder> subfolders = new ArrayList<Folder>();
	private Folder parentFolder;

	private Date lastUpdate;

	public Folder(Account account, String name, boolean isImapFolder, Folder parentFolder)
	{
		this.account = account;
		this.name = name;
		this.isImapFolder = isImapFolder;
		this.parentFolder = parentFolder;
	}

	public void setLastUpdate(Date lastUpdate) {
		this.lastUpdate = lastUpdate;
	}

	public boolean isImapFolder() {
		return isImapFolder;
	}

	public ArrayList<Mail> getMails()
	{
		return mails;
	}

	public void setMails(ArrayList<Mail> mails)
	{
		this.mails = mails;
	}

	public Account getAccount() {
		return account;
	}

	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return name;
	}

	public void addMail(Mail c) {
		mails.add(c);
		Collections.sort(mails);
	}

	@Override
	public boolean equals(Object obj) {

		if(obj instanceof Folder)
		{
			return ((Folder) obj).getName().equals(this.getName());
		}

		return super.equals(obj);
	}

	public boolean containsMail(Mail m)
	{
		if(mails.contains(m))
		{
			return true;
		}else
		{
			for(Folder subFolder : subfolders)
			{
				if(subFolder.containsMail(m))
				{		
					return true;
				}
			}
		}
		return false;
	}

	public void addSubFolder(Folder folder) {
		subfolders.add(folder);
	}


	public MutableTreeNode getNode() {
		DefaultMutableTreeNode node = new DefaultMutableTreeNode(getName());
		node.setUserObject(this);

		for(Folder subFolder : subfolders)
		{
			node.add(subFolder.getNode());
		}

		return node;
	}

	public Folder getParentFolder() {
		return parentFolder;
	}

	public void setParentFolder(Folder parentFolder)
	{
		this.parentFolder = parentFolder;
	}

	public boolean needsRefresh() {
		Date now = new Date();

		if(lastUpdate != null)
		{
			return (now.getTime() - lastUpdate.getTime()) > 60*1000*5;
		}
		else{
			return true;
		}

	}

	public void removeSubFolder(Folder selectedFolder) {
		subfolders.remove(selectedFolder);		
	}

	public void addMails(ArrayList<Mail> mails2) {
		mails.addAll(mails2);
		Collections.sort(mails);
		
	}


}
